<template>
    <div class="admin-users">
        <h1 class="page-title">用户管理</h1>

        <div class="toolbar">
            <el-input v-model="searchQuery" placeholder="搜索用户名/邮箱" class="search-input" clearable @clear="handleSearch">
                <template #suffix>
                    <el-icon class="el-input__icon" @click="handleSearch">
                        <Search />
                    </el-icon>
                </template>
            </el-input>

            <div class="action-group">
                <el-button type="primary" @click="handleAddUser">
                    <el-icon>
                        <Plus />
                    </el-icon> 添加用户
                </el-button>
            </div>
        </div>

        <el-table :data="userList" style="width: 100%" v-loading="loading">
            <el-table-column prop="id" label="ID" width="200" />
            <el-table-column prop="username" label="用户名" width="120" />
            <el-table-column prop="email" label="邮箱" width="180" />
            <el-table-column prop="role" label="角色" width="100">
                <template #default="scope">
                    <el-tag :type="scope.row.role === 'admin' ? 'danger' : 'primary'">
                        {{ scope.row.role === 'admin' ? '管理员' : '用户' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                    <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
                        {{ scope.row.status === 'active' ? '正常' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="registerTime" label="注册时间" width="180">
                <template #default="scope">
                    {{ formatDate(scope.row.createTime) }}
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="最后更新时间" width="180">
                <template #default="scope">
                    {{ formatDate(scope.row.updateTime) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="280">
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="warning" @click="handleResetPassword(scope.row)"
                        :disabled="scope.row.role === 'admin'">
                        重置密码
                    </el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)"
                        :disabled="scope.row.role === 'admin'">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination-container">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 用户编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑用户' : '添加用户'" width="500px">
            <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="100px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="userForm.username" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userForm.email" />
                </el-form-item>
                <el-form-item label="密码" prop="password" v-if="!isEdit">
                    <el-input v-model="userForm.password" type="password" show-password />
                </el-form-item>
                <el-form-item label="角色" prop="role">
                    <el-select v-model="userForm.role" placeholder="请选择角色">
                        <el-option label="普通用户" value="user" />
                        <el-option label="管理员" value="admin" />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select v-model="userForm.status" placeholder="请选择状态">
                        <el-option label="正常" value="active" />
                        <el-option label="禁用" value="inactive" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/utils/request'
import list from '@/utils/url'

// 用户列表数据
const userList = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索相关
const searchQuery = ref('')
const loading = ref(false)

// 表单相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const userFormRef = ref(null)
const userForm = ref({
    id: null,
    username: '',
    email: '',
    password: '',
    role: 'user',
    status: 'active'
})

// 表单验证规则
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于 6 个字符', trigger: 'blur' }
    ],
    role: [
        { required: true, message: '请选择角色', trigger: 'change' }
    ],
    status: [
        { required: true, message: '请选择状态', trigger: 'change' }
    ]
}

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return ''
    const date = new Date(dateString)
    return date.toLocaleString()
}

// 处理搜索
const handleSearch = () => {
    loading.value = true
    // 模拟搜索请求
    setTimeout(() => {
        // 实际项目中应该调用API进行搜索
        if (searchQuery.value) {
            const filteredUsers = userList.value.filter(user =>
                user.username.includes(searchQuery.value) ||
                user.email.includes(searchQuery.value)
            )
            userList.value = filteredUsers
        } else {
            // 重置为原始数据
            fetchUserList()
        }
        loading.value = false
    }, 500)
}

// 处理分页大小变化
const handleSizeChange = (val) => {
    pageSize.value = val
    fetchUserList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchUserList()
}

// 添加用户
const handleAddUser = () => {
    isEdit.value = false
    userForm.value = {
        id: null,
        username: '',
        email: '',
        password: '',
        role: 'user',
        status: 'active'
    }
    dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
    isEdit.value = true
    userForm.value = {
        ...row,
        password: '' // 编辑时不显示密码
    }
    dialogVisible.value = true
}

// 删除用户
const handleDelete = (row) => {
    ElMessageBox.confirm(
        `确定要删除用户 ${row.username} 吗？`,
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        http.delete(`${list.list_admin_api.deleteUser}/${row.id}`)
            .then((response) => {
                if (response.code === 200) {
                    const index = userList.value.findIndex(item => item.id === row.id)
                    if (index !== -1) {
                        userList.value.splice(index, 1)
                        total.value--
                        ElMessage.success('删除成功')
                    }
                } else {
                    ElMessage.error(response.data.msg || '删除失败')
                }
            })
    })
        .catch(() => {
            // 取消删除
            ElMessage.info('操作取消')
        })
}

// 提交表单
const submitForm = () => {
    userFormRef.value.validate((valid) => {
        if (valid) {
            if (isEdit.value) {
                // 编辑用户
                http.post(list.list_admin_api.editUser, userForm.value)
                    .then((response) => {
                        if (response.code === 200) {
                            const index = userList.value.findIndex(item => item.id === userForm.value.id)
                            if (index !== -1) {
                                userList.value[index] = { ...userForm.value }
                                ElMessage.success('用户信息更新成功')
                            }
                        }
                    }).catch((error) => {
                        ElMessage.error('更新用户失败')
                    })

            } else {
                // 添加用户
                http.put(list.list_admin_api.addUser, userForm.value)
                    .then((response) => {
                        if (response.code === 200) {
                            //最最前面添加
                            userList.value.unshift(response.data)
                            total.value++
                            ElMessage.success('用户添加成功')
                        }
                    }).catch((error) => {
                        ElMessage.error('添加用户失败')
                    })
            }
            dialogVisible.value = false
        }
    })
}

onMounted(() => {
    // 获取用户列表数据
    fetchUserList()
})

// 获取用户列表数据
const fetchUserList = async () => {
    loading.value = true
    try {
        const response = await http.get(`${list.list_admin_api.getUsersByPage}/${currentPage.value}/${pageSize.value}`)
        if (response.code === 200) {
            userList.value = response.data.records
            total.value = response.data.total
        } else {
            ElMessage.error(response.data.msg || '获取用户列表失败')
        }
    } catch (error) {
        console.error('获取用户列表失败:', error)
        ElMessage.error('获取用户列表失败')
    } finally {
        loading.value = false
    }
}

// 重置用户密码
const handleResetPassword = (user) => {
    ElMessageBox.confirm(
        `确定要重置用户  ${user.username}  的密码吗？`,
        '重置密码',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            const response = await http.post(`${list.list_admin_api.resetUserPassword}/${user.id}`)
            if (response.code === 200) {
                const resetData = response.data
                ElMessageBox.alert(
                    `用户 <strong>${resetData.username}</strong> 的密码已重置为：<strong>${resetData.newPassword}</strong>`,
                    '密码重置成功',
                    {
                        dangerouslyUseHTMLString: true,
                        confirmButtonText: '确定',
                        type: 'success'
                    }
                )
            } else {
                ElMessage.error(response.data.msg || '重置密码失败')
            }
        } catch (error) {
            console.error('重置密码失败:', error)
            ElMessage.error('重置密码失败')
        }
    }).catch(() => {
        // 用户取消操作
        ElMessage.info('操作已取消')
    })
}
</script>

<style scoped>
.admin-users {
    padding: 20px;
}

.page-title {
    margin-bottom: 20px;
    font-size: 24px;
    color: #303133;
}

.toolbar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    align-items: center;
}

.search-input {
    width: 300px;
}

.action-group {
    display: flex;
    gap: 15px;
    align-items: center;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>